package com.ice.app.base.authorization.service;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import com.ice.app.base.authorization.entity.UserSecurtiyDetails;
import com.ice.app.system.entity.User;
import com.ice.app.system.role.service.RoleService;
import com.ice.app.system.user.service.UserService;

@Component("userSecurityService")
public class UserSecurityService implements UserDetailsService {

	@Autowired
    UserService userService;
	
    @Autowired
    RoleService roleService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = userService.getUserByUsername(username);
        if (user == null) {
            throw new UsernameNotFoundException("username not found");
        }
//        List<String> roles = roleService.getValidRolesByUserId(user.getUserId());
        UserSecurtiyDetails userSecurityDetails = this.getUserSecurityDetails(user, new ArrayList<String>());
        return userSecurityDetails;
    }
	
	private UserSecurtiyDetails getUserSecurityDetails(User user,List<String> roles) {
		UserSecurtiyDetails userSecurtiyDetails = new UserSecurtiyDetails();
		userSecurtiyDetails.setUserId(user.getUserId());
		userSecurtiyDetails.setUsername(user.getUsername());
	    userSecurtiyDetails.setPassword(user.getPassword());
	    userSecurtiyDetails.setSalt(user.getSalt());
	    userSecurtiyDetails.setEmail(user.getEmail());
	    userSecurtiyDetails.setMobile(user.getMobile());
	    userSecurtiyDetails.setStatus(user.getStatus());
	    userSecurtiyDetails.setOrganId(user.getOrganId());
	    userSecurtiyDetails.setCreateBy(user.getCreateBy());
	    userSecurtiyDetails.setCreateDate(user.getCreateDate());
	    userSecurtiyDetails.setUpdateBy(user.getUpdateBy());
	    userSecurtiyDetails.setUpdateDate(user.getUpdateDate());
	    userSecurtiyDetails.setRemark(user.getRemark());
		userSecurtiyDetails.setRoles(roles);
		return userSecurtiyDetails;
	}
}
